﻿namespace Pub.Class
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    public class PostStack
    {
        public static int Length = 50;
        public static IList<PostStackInfo> list = new List<PostStackInfo>();
        public static int MaxPosts = 0;
        public static int MaxSecond = 5;

        public static void Clear()
        {
            list.Clear();
        }

        public static void Run()
        {
            Run(string.Empty);
        }

        public static void Run(string op)
        {
            DateTime now;
            string ip;
            if (MaxPosts != 0)
            {
                op = op.IsNullEmpty() ? "_sys_op_" : op;
                now = DateTime.Now;
                ip = Request2.GetIP();
                if ((from p in list
                    where ((p.Time.GetTimeSpan(now).Seconds < MaxSecond) && (ip == p.IP)) && (p.Op == op)
                    select p).Count<PostStackInfo>() >= MaxPosts)
                {
                    Msg.WriteEnd("限制{0}秒内不能相同操作".FormatWith(MaxSecond));
                }
                PostStackInfo item = new PostStackInfo {
                    IP = ip,
                    Time = now,
                    Op = op
                };
                list.Add(item);
                if (list.Count<PostStackInfo>() > Length)
                {
                    list.RemoveAt(0);
                }
            }
        }

        public static void RunContent(string content)
        {
            RunContent(string.Empty, content);
        }

        public static void RunContent(string op, string content)
        {
            op = op.IsNullEmpty() ? "_sys_op_" : op;
            DateTime now = DateTime.Now;
            string ip = Request2.GetIP();
            if ((from p in list
                where ((ip == p.IP) && (p.Op == op)) && (p.Content == content)
                select p).Count<PostStackInfo>() > 0)
            {
                Msg.WriteEnd("不能提交相同的内容");
            }
            PostStackInfo item = new PostStackInfo {
                IP = ip,
                Time = now,
                Op = op,
                Content = content
            };
            list.Add(item);
            if (list.Count<PostStackInfo>() > Length)
            {
                list.RemoveAt(0);
            }
        }
    }
}

